package com.study.sbsummary.dao;

import com.study.sbsummary.model.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/***
 * Spring JdbcTemplate是对原生jdbc的改进
 * */
@Repository
@Primary
public class OrderDaoImpl implements OrderDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int insert(Order order) {
        int update = jdbcTemplate.update("insert into t_order (id,money,user_id,receiver_address,receiver_name," +
                        "receiver_phone) values(?,?,?,?,?,?)",
                order.getId(), order.getMoney(),
                order.getUserId(), order.getReceiverAddress(),
                order.getReceiverName(), order.getReceiverPhone());
        return update;
    }

    @Override
    public int update(Order order) {
        int update = jdbcTemplate.update("update t_order set money = ?,user_id = ?,receiver_address=?," +
                        "receiver_name=?, receiver_phone=?" +
                        "where id = ?", order.getMoney(),
                order.getUserId(), order.getReceiverAddress(),
                order.getReceiverName(), order.getReceiverPhone(), order.getId());
        return update;
    }

    @Override
    public List<Order> selectAll() {
        String sql = "select * from t_order";
        List<Order> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Order.class));
        return list;
    }

    @Override
    public Order selectById(Long id) {
        String sql = "select * from t_order where id = ?";
        Order order = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Order.class), id);
        return order;
    }
}

// java 原生jdbc https://blog.csdn.net/qq_42873554/article/details/104925008
/*
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        sql = null;

        try {
            sql = "";

            conn = JDBCUtils.getConnection();

           // st = conn.createStatement();
            ps = conn.prepareStatement();

            rs = st.executeQuery("");

            while (rs.next()){
                System.out.println(rs.getObject(1)+"\t"
                        +rs.getObject("id"));  // 建议用列名
            }
        }finally {
            JDBCUtils.free(rs,st,conn);
        }
* */
